import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/About.vue')
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "test" */ '../views/Login.vue')
  },
  {
    path: '/pricelist',
    name: 'PriceList',
    component: () => import(/* webpackChunkName: "test" */ '../views/PriceList.vue')
  }
]

const router = new VueRouter({
  mode: 'history',  // 默认是hash模式，路径后边会带/#/号，所以需要改成history模式。改成history会出现空白页，需要后端nginx部署配合
  // https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子
  base: process.env.BASE_URL,
  // base: './',
  routes
})

// 设置路由守卫，如果用户在访问前，没有得到这个响应头，让其跳转到登录页重新登录
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === 'login') {
    console.log(to.path)
    next();
  } else {
    let token = localStorage.getItem('Authorization');
    if (token === 'null' || token === '' || token === null) {
      next('/login');
      // this.$router.push({ path: "/login" });
      // next(false) 阻止跳转 中断导航
    } else {
      next();
    }
  }
});

export default router
